package com.webull.information.center.carwler.task.handler;

import com.webull.information.center.carwler.common.model.NewsInformation;
import com.webull.information.center.carwler.common.model.StockConfig;
import com.webull.information.center.carwler.common.model.StockTitle;
import com.webull.information.center.carwler.common.util.jsoup.HttpJsoupClient;
import com.webull.information.center.carwler.common.util.news.YahooNewsListUitl;
import com.webull.information.center.carwler.common.util.news.YahooNewsListUitl.YahooItem;
import com.webull.information.center.carwler.task.support.StockConfigSupport;
import com.webull.information.center.carwler.task.support.TikcerNewsProcessor;
import com.webull.information.center.common.constants.Constants;
import com.webull.information.center.common.constants.UrlConstants;
import com.webull.information.client.model.News;
import com.webull.information.client.model.parm.NewsRelType;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * yahoo新闻
 * 
 * @author shimingjun
 * @date 2017年3月7日 下午1:47:35
 * @version 1.0
 * @since JDK 1.8
 */
@Component
public class StockYahooNewsHandler {

	protected final Logger logger = LogManager.getLogger(getClass());
	private static String yahoo_lang = Constants.lang_en;// 新浪语言版本
	private @Autowired YahooNewsListUitl yahooNewsListUitl;
	private @Autowired StockConfigSupport stockConfigSupport;

	private @Autowired
    TikcerNewsProcessor tikcerNewsProcessor;

	private Integer[] zhantRegions = new Integer[] { 1, 2, 6 };

	public void handlerByStockTitle4Yahoo(StockTitle stockTitle) {

		String googSymbol = tikcerNewsProcessor.googleSymbol(stockTitle.getTickerId(), stockTitle.getSymbol());
		String yahooExchange = tikcerNewsProcessor.yahooExchage(stockTitle.getExchangeId(),
				"");
		if( !Integer.valueOf(6).equals(stockTitle.getRegionId()) &&  StringUtils.isBlank(yahooExchange)) {
			logger.info("stockTitle :{} 's yahooExchange is not support!!!",stockTitle);
			return;
		}
		{
			StockConfig stockConfig = stockConfigSupport.getStockConfig(stockTitle, "yahoo_en", yahoo_lang);
			String newsProfile = getYhooProfileUrl(stockTitle.getRegionId(), yahooExchange, googSymbol);
			processYahooList(stockConfig, stockTitle, newsProfile);
		}
		/*
		 * 中港美的繁体
		 */

		if (ArrayUtils.contains(zhantRegions, stockTitle.getRegionId())) {
			StockConfig stockConfig = stockConfigSupport.getStockConfig(stockTitle, "yahoo_en", Constants.lang_zh_hant);
			String newsProfile = getYhooHKProfileUrl(stockTitle.getRegionId(), yahooExchange, googSymbol);
			processYahooZhantList(stockConfig, stockTitle, newsProfile);
		}

	}

	private void processYahooList(StockConfig stockConfig, StockTitle stockTitle, String newsProfile) {
		try {
			List<Date> times = new ArrayList<>();
			Date lastPush = stockConfig.getCollectTime();
			/**
			 * 获取标的物新闻首页列表
			 */
			List<YahooItem> newsList = yahooNewsListUitl.parseNewsList(newsProfile);
			//
			entrie: for (int i = 0; newsList != null && i < newsList.size(); i++) {
				try {
					YahooItem item = newsList.get(i);
					Date push = item.getNewsTime();
					if (push == null) {
						logger.warn("-processSinaList stockTitle:{}, url:{} YahooItem{}, push can't be parse!!",
								stockTitle, newsProfile, item);
						continue entrie;
					}

					if (lastPush == null || DateUtils.isSameDay(push, new Date()) || push.after(lastPush)) {
						times.add(push);
						processYahooNews(stockTitle, item);
					}
				} catch (Exception e) {
					logger.warn(e);
					break entrie;
				}
			}

			if (!times.isEmpty()) {
				tikcerNewsProcessor.updateStockConfig(stockConfig,times);
				stockConfigSupport.updateById(stockConfig);
			}

		} catch (Exception e) {
			stockConfig.setCollectNumber(-99);
			stockConfigSupport.updateById(stockConfig);
			logger.error("processYahooList(Date lastPush, StockTitle stockTitle, String compFinanceRss)", e);
		}
	}

	private void processYahooZhantList(StockConfig stockConfig, StockTitle stockTitle, String newsProfile) {
		try {
			List<Date> times = new ArrayList<>();
			Date lastPush = stockConfig.getCollectTime();
			/**
			 * 获取标的物新闻首页列表
			 */
			List<YahooItem> newsList = yahooNewsListUitl.parseZhantNewsList(newsProfile);
			//
			entrie: for (int i = 0; newsList != null && i < newsList.size(); i++) {
				try {
					YahooItem item = newsList.get(i);
					Date push = item.getNewsTime();
					if (push == null) {
						logger.warn("-processYahooZhantList stockTitle:{}, url:{} YahooItem{}, push can't be parse!!",
								stockTitle, newsProfile, item);
						continue entrie;
					}

					if (lastPush == null || DateUtils.isSameDay(push, new Date()) || push.after(lastPush)) {
						times.add(push);
						processYahooNews(stockTitle, item);
					}
				} catch (Exception e) {
					logger.warn(e);
					break entrie;
				}
			}

			if (!times.isEmpty()) {
				tikcerNewsProcessor.updateStockConfig(stockConfig,times);
				stockConfigSupport.updateById(stockConfig);
			}

		} catch (Exception e) {
			stockConfig.setCollectNumber(-99);
			stockConfigSupport.updateById(stockConfig);
			logger.error("processYahooZhantList(Date lastPush, StockTitle stockTitle, String compFinanceRss)", e);
		}
	}

	private void processYahooNews(StockTitle stockTitle, YahooItem item) throws Exception {
		String title = item.getTitle();
		String link = item.getLink();
		// SyndContent description = entry.getDescription();
		NewsInformation info = new NewsInformation();// produce(doc);
		info.setCollectSource(News.CollectSource.Yahoo);
		info.setSiteType(News.SiteType.PIRORIT);
		info.setTitle(title);
		info.setRegionId(stockTitle.getRegionId());

		info.setNewsTime(item.getNewsTime());
		info.setUrl(link);
		info.setLanguage(Optional.ofNullable(item.getLang()).orElse(yahoo_lang));
		/*
		 * 主图
		 */
		Optional.ofNullable(StringUtils.stripToNull(item.getMainPic()))//
				.ifPresent(v00 -> info.addMainPic(v00));

		info.setSourceName(item.getSource());
		String md5 = HttpJsoupClient.finishingMd5Url(link);
		info.setUrlMd5(md5);

		tikcerNewsProcessor.bindTargetNewsRecord(info, stockTitle.getTickerId(), NewsRelType.ticker);
	}

	/**
	 *  转换成CNBC的新闻列表url
	 *
	 * <pre>
	 * 目前只支持美股
	 * </pre>
	 * @param regionId
	 * @param exchange
	 * @param yahoSymbol
	 * @return
	 */
	private static String getYhooProfileUrl(Integer regionId, String exchange, String yahoSymbol) {
		if (Integer.valueOf(2).equals(regionId)) // 香港
			yahoSymbol = StringUtils.substring(yahoSymbol, -4);

		if (Integer.valueOf(6).equals(regionId)) // 美国
			return StringUtils.replaceOnce(UrlConstants.yahooNewsUnitUrl, "{symbol}", yahoSymbol);

		return StringUtils.replaceOnce(UrlConstants.yahooNewsUnitUrl, "{symbol}", yahoSymbol + "." + exchange);
	}

	private static String getYhooHKProfileUrl(Integer regionId, String exchange, String yahoSymbol) {
		if (Integer.valueOf(2).equals(regionId)) // 香港
			yahoSymbol = StringUtils.substring(yahoSymbol, -4);

		if (Integer.valueOf(6).equals(regionId)) // 美国
			return StringUtils.replaceOnce(UrlConstants.yahooHKNewsUnitUrl, "{symbol}", yahoSymbol);

		return StringUtils.replaceOnce(UrlConstants.yahooHKNewsUnitUrl, "{symbol}", yahoSymbol + "." + exchange);
	}

}
